import React, { useState, useRef, useCallback } from 'react'
import { Button, Card, message, Progress, Alert } from 'antd'
import { AudioOutlined, AudioMutedOutlined, StopOutlined } from '@ant-design/icons'
import apiService from '../services/api'

function VoiceRecorder() {
  const [isRecording, setIsRecording] = useState(false)
  const [recordingTime, setRecordingTime] = useState(0)
  const [isProcessing, setIsProcessing] = useState(false)
  const [asrResult, setAsrResult] = useState(null)

  const mediaRecorderRef = useRef(null)
  const audioChunksRef = useRef([])
  const timerRef = useRef(null)

  // 开始录音
  const startRecording = useCallback(async () => {
    try {
      // 请求麦克风权限
      const stream = await navigator.mediaDevices.getUserMedia({
        audio: {
          sampleRate: 16000,
          channelCount: 1,
          echoCancellation: true,
          noiseSuppression: true
        }
      })

      // 创建 MediaRecorder
      const mediaRecorder = new MediaRecorder(stream, {
        mimeType: 'audio/webm;codecs=opus'
      })

      mediaRecorderRef.current = mediaRecorder
      audioChunksRef.current = []

      // 收集音频数据
      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunksRef.current.push(event.data)
        }
      }

      // 录音结束
      mediaRecorder.onstop = async () => {
        const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/webm' })

        // 停止所有音轨
        stream.getTracks().forEach(track => track.stop())

        // 处理录音结果
        await processRecording(audioBlob)
      }

      // 开始录音
      mediaRecorder.start(100) // 每100ms收集一次数据
      setIsRecording(true)
      setRecordingTime(0)

      // 启动计时器
      timerRef.current = setInterval(() => {
        setRecordingTime(prev => prev + 1)
      }, 1000)

      message.info('开始录音，请说话...')

    } catch (error) {
      console.error('Failed to start recording:', error)
      message.error('无法访问麦克风，请检查权限设置')
    }
  }, [])

  // 停止录音
  const stopRecording = useCallback(() => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop()
      setIsRecording(false)

      if (timerRef.current) {
        clearInterval(timerRef.current)
        timerRef.current = null
      }

      message.info('录音结束，正在处理...')
    }
  }, [isRecording])

  // 处理录音结果
  const processRecording = useCallback(async (audioBlob) => {
    if (audioBlob.size < 1000) {
      message.warning('录音时间太短，请重新录音')
      return
    }

    setIsProcessing(true)

    try {
      // 调用语音识别 API
      const response = await apiService.uploadAudioForASR(audioBlob)

      if (response.success) {
        setAsrResult(response.data)
        message.success('语音识别完成')

        // 将识别结果传递给父组件
        if (window.onASRResult) {
          window.onASRResult(response.data)
        }
      } else {
        throw new Error(response.error || '语音识别失败')
      }
    } catch (error) {
      console.error('ASR processing failed:', error)
      message.error(`语音识别失败: ${error.message}`)
      setAsrResult(null)
    } finally {
      setIsProcessing(false)
    }
  }, [])

  // 格式化录音时间
  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  // 清理资源
  const cleanup = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current)
      timerRef.current = null
    }

    if (mediaRecorderRef.current) {
      mediaRecorderRef.current = null
    }

    setIsRecording(false)
    setRecordingTime(0)
    setAsrResult(null)
  }, [])

  // 组件卸载时清理
  React.useEffect(() => {
    return cleanup
  }, [cleanup])

  return (
    <div>
      <Card
        title="🎤 语音录制 (ASR)"
        size="small"
        style={{ marginBottom: 16 }}
      >
        {/* 录音控制按钮 */}
        <div style={{ marginBottom: 16 }}>
          {!isRecording ? (
            <Button
              type="primary"
              icon={<AudioOutlined />}
              onClick={startRecording}
              disabled={isProcessing}
              style={{ width: '100%', height: 48 }}
            >
              开始录音
            </Button>
          ) : (
            <Button
              danger
              icon={<StopOutlined />}
              onClick={stopRecording}
              style={{ width: '100%', height: 48 }}
            >
              停止录音 ({formatTime(recordingTime)})
            </Button>
          )}
        </div>

        {/* 录音状态指示 */}
        {isRecording && (
          <div style={{ marginBottom: 16 }}>
            <Progress
              percent={(recordingTime % 60) / 60 * 100}
              status="active"
              strokeColor="#1890ff"
              showInfo={false}
            />
            <div style={{
              textAlign: 'center',
              marginTop: 8,
              color: '#1890ff',
              fontWeight: 500
            }}>
              🎙️ 正在录音... {formatTime(recordingTime)}
            </div>
          </div>
        )}

        {/* 处理状态 */}
        {isProcessing && (
          <Alert
            message="正在处理语音..."
            description="请稍候，正在将语音转换为文字"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        {/* 语音识别结果 */}
        {asrResult && (
          <Alert
            message="🎯 语音识别结果"
            description={
              <div>
                <p><strong>识别文字:</strong> "{asrResult.text}"</p>
                <p><strong>置信度:</strong> {(asrResult.confidence * 100).toFixed(1)}%</p>
                <p><strong>语言:</strong> {asrResult.language}</p>
              </div>
            }
            type="success"
            showIcon
            closable
            onClose={() => setAsrResult(null)}
          />
        )}

        {/* 使用提示 */}
        <div style={{
          padding: 12,
          background: '#f6ffed',
          border: '1px solid #b7eb8f',
          borderRadius: 6,
          fontSize: 12,
          color: '#52c41a'
        }}>
          <strong>💡 使用提示:</strong>
          <ul style={{ margin: '8px 0 0 0', paddingLeft: 20 }}>
            <li>点击"开始录音"后请对麦克风说话</li>
            <li>录音最长支持60秒</li>
            <li>支持中文普通话识别</li>
            <li>识别完成后会自动填充到聊天框</li>
          </ul>
        </div>
      </Card>
    </div>
  )
}

export default VoiceRecorder
